package com.dashang.util.common.tag;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dashang.util.common.SystemConstant;

/**
 * 获取国际化资源tag
 *
 * @author 陈兴
 * @version [版本号, 2011-8-21]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ResourceTag extends TagSupport {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -1573040049527714803L;

	/**
	 * 日志记录
	 */
	private static final Log log = LogFactory.getLog(ResourceTag.class);

	/**
	 * 国际化文件
	 */
	private String messageProp;

	/**
	 * 国际化key
	 */
	private String key;

	/**
	 * 语言
	 */
	private String language;

	/**
	 * 参数
	 */
	private String param;

	public int doStartTag() throws JspException {
		if (StringUtils.isNotEmpty(key)) {
			Locale locale = null;
			if (StringUtils.isNotEmpty(language)) {
				locale = new Locale(language);
			} else {
				// 获取系统默认语言
				locale = new Locale(SystemConstant.DEFAULT_LANGUAGE);
			}
			if (StringUtils.isEmpty(messageProp)) {
				// 设置默认资源文件
				messageProp = SystemConstant.DEFAULTRE_SOURCE_PROP;
			}
			try {
				// 获取国际化资源
				String messageStr = Resource.getResource(messageProp, key,
						locale);
				if (StringUtils.isEmpty(messageStr)) {
					// 如果获取不到资源文字，则原样输出key值
					pageContext.getOut().print(key);
				} else {
					if (StringUtils.isEmpty(param)) {
						pageContext.getOut().print(messageStr);
					} else {
						String[] params = param.split(","); // 使用参数填充{n}占位符
						String message = MessageFormat.format(messageStr,
								params);
						pageContext.getOut().print(message);

					}
				}
			} catch (IOException e) {
				log.error(e);
			} catch (Exception e) {
				log.error(e);
				try {
					pageContext.getOut().print(key);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		} else {
			log.warn("ResourceTag.key is Empty!");
		}

		return EVAL_BODY_INCLUDE;
	}

	public String getMessageProp() {
		return messageProp;
	}

	public void setMessageProp(String messageProp) {
		this.messageProp = messageProp;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

}
